/**
 * 权限菜单管理JS
 * 
 */
var parentId = 0;
var permissionName = '权限菜单';//父节点名称
var permissionLeaf = false;//是否为节点
var permissionDataTable;//数据表
var nodeDataTable;
var permissionLeafCount=0;
var setting;//Ztree设置

$(function () {
//	$('#permissionDataTableDiv').show();
//	$('#nodeDataTableDiv').hide();
	setting = {data:{simpleData:{enable : true,idKey : "permissionId",pIdKey : "permissionParentId",rootPId:null},key:{name:"permissionName",leaf:'permissionLeaf',urlLink:"permissionUrl",ext:"permissionExt1",order:"permissionOrder"}},callback:{onClick: zTreeOnClick}};
	reloadTree();//数据表据重新加载
	//数节点点击回调函数
	function zTreeOnClick(event, treeId, treeNode){
		parentId = treeNode.permissionId;
		permissionName = treeNode.permissionName;
		permissionLeafCount = treeNode.permissionLeaf;
		permissionLeaf = (treeNode.permissionLeaf!=0);
		$('#permissionDataTableDiv').show();
		permissionDataTable.ajax.reload();
	};
	
	 //权限数据表
	 permissionDataTable = $('#permissionDataTable').DataTable({
		 	"bProcessing": true,
	        "bLengthChange":true,
	        "bFilter": false,//无搜索 
	        "bServerSide": true,//服务端数据处理
	        "bSort": false,//排序功能
	        "pagingType":"full_numbers",
	        "sAjaxSource": "../power/queryPermissionsCondition",//后端服务地址
	        "fnServerParams" : function(aDataSet) {aDataSet.push({"name" : "parentId","value" : parentId});},
	        "fbServerData":function(sSource,aDataSet){$.ajax({"dataType":"json","type":"GET","url":sSource,"data":aDataSet});},
	        "aoColumns":[{"mDataProp":"permissionName"},{"mDataProp":"permissionOrder"},{"mDataProp":"permissionUrl"},{"mDataProp":"permissionAction"},{"mDataProp":"permissionExt1"},{"mDataProp":"permissionId"}],
	        "aoColumnDefs":[{"aTargets":[3],"mRender":function(data,type,full){return "<i class='"+data+"'></i>"}},
	     	               {"aTargets":[5],"mRender":function(data,type,full) {
	//         	            	  var updateDataBtn="<button class='btn btn-lightblue btn-outline m-wrap' full-id='"+full.teacherId+"' data-id='"+data+"' id='updateDataBtn' style='font-size:12px;line-height:15px;'><i class='icon-pencil'></i></button>  ";
	     	            	   return "<button class='btn btn-lightblue btn-outline m-wrap' style='font-size:12px;line-height:15px;' data-id='"+data+"' data-json='"+JSON.stringify(full)+"' data-name='"+full.permissionName+"' id='uptBtn'><i class='icon-pencil'></i></button>" +
	     	            	  "&nbsp;&nbsp;"+"<button class='btn btn-lightpink btn-outline m-wrap' style='font-size:12px;line-height:15px;' data-id='"+data+"' data-name='"+full.permissionName+"' id='dltBtn'><i class='icon-remove'></i></button>";}
	        }],
	        "oLanguage":{"sUrl": "../resources/assets/plugins/dataTables/txt/page.txt"},
	     "initComplete":function () {
	         $('#permissionDataTable_length').find('select').selectpicker('render');
	         $('#permissionDataTable_length').find('select').selectpicker('refresh');
	         $('#permissionDataTable_length').find('.btn-group').css('width','auto');
	         $('#permissionDataTable_length').find('.btn').css('background-color','#fff');
	         $('#permissionDataTable_length').find('.btn').css('border','#d8d8d8 solid 1px')
	     }
	});
     
    //删除功能菜单操作
 	$('#permissionDataTable tbody').on('click','#dltBtn',function(){
		var name = $(this).attr("data-name");
		var id = $(this).attr("data-id");
		confirm("您确定删除["+name+"]角色？", function(isConfirm){
			if (isConfirm) {$.post("../power/deletePermission?permissionId="+id,function(data){if(data){reloadTree();permissionDataTable.ajax.reload();swal("成功", "当前操作成功 :)", "success");}else{swal("失败", data.errorMsg, "error");}});} 
			else {swal("取消", "您的操作已经取消 :)", "error");}
		});
 	});
 	
 	$('#permissionDataTable tbody').on('click','#uptBtn',function(){
 		var json = $.parseJSON($(this).attr("data-json"));
 		
 		$("#permissionInfoDiv .modal-body").html(permissionInfoDiv(parentId,permissionName,json));
 		if(json.permissionType!=null){
 			$('#permissionType').val(json.permissionType);
 		}
 		$("#permissionInfoForm").validate({
 			  errorElement: 'span',
 			  errorClass:'help-inline',
 			  focusInvalid: false,ignore: '',
 			  rules: {permissionName: {minlength: 2,required: true,maxlength:20,
 				                 remote:{type:'post',url:'../power/checkPermissionName',data: {permissionName:function(){return $("#permissionName").val();}},
 				                	     dataType: "json",dataFilter:function (data) { if(json.permissionName == $("#permissionName").val()) return true; return  data=='false'?true:false;}}},
 				      permissionOrder:{number:true,required:true},
 				      permissionExt1:{required:true},
 				      tag:{required:true},
 				      permissionDesc:{required:true},
 				      permissionUrl:{checkPost:true}},
 		      messages:{permissionName:{remote:'节点名已经存在,请重新变更'}},
 			  errorPlacement: function(error,element){error.insertAfter(element);},
 			 highlight: function(element) {
 	   			  $(element).closest('.control-group').removeClass('success');
 	   			  $(element).closest('.help-inline').removeClass('valid');
 	   			  $(element).closest('.help-inline').removeClass('ok');
 	   			  $(element).closest('.control-group').addClass('error');
 	   		  },
 				  unhighlight: function(element) {$(element).closest('.control-group').removeClass('error');},
 				  success: function(label) {
 					  label.closest('.control-group').removeClass('error');
 					  label.closest('.control-group').addClass('success');
 					  label.closest('.help-inline').addClass('valid ok');
 				  },
 			  submitHandler:function(form){
 				  $.post('../power/updatePermission',$("#permissionInfoForm").serialize(),function(data){
 					  if(data.flg){
 						  $("#permissionInfoDiv").modal("hide");
 						  reloadTree();permissionDataTable.ajax.reload();
 						  swal("", "当前操作成功 :)", "success");
 					  }else{
 						  swal("取消", data.error, "error");
 					  }
 				  });
 			      return false;
 			  }});
 		if($('#permissionType').val()=='1'){
 			$('#permissionExtSpan').text('菜单编号');
 			$('#cdtpDiv').show();
 			$('#ljdxDiv').show();
 		}else if($('#permissionType').val()=='2'){
 			$('#permissionExtSpan').text('AclId');
 			$('#cdtpDiv').hide();
 			$('#ljdxDiv').hide();
 		}
 		
 		$("#permissionInfoDiv").modal("show");
 	});
 	
 	$("#permissionAddBtn").click(function(){$("#permissionInfoForm").submit();});
 	
 	$("#savePermssion").click(function(){
 		if(permissionLeafCount=='1'){
 			swal("失败", "当前节点为叶子节点不能在增加子节点 :)", "error");
 			return;
 		}
 		
 		if(permissionLeaf){
 			$('#nodeInfoDiv').modal("show");
 			$('#nodeElseName').val('');
 			$('#nodeElseOrder').val('');
 			$('#aclId').val('');
 			$('#permissionParentName').val(permissionName);
 			return;
 		}
 		$("#permissionInfoDiv .modal-body").html(permissionInfoDiv(parentId,permissionName));
 		
 		$('#permissionType').change(function(){
 	 		if($('#permissionType').val()=='1'){
 	 			$('#permissionExtSpan').text('菜单编号');
 	 			$('#cdtpDiv').show();
 	 			$('#ljdxDiv').show();
 	 		}else if($('#permissionType').val()=='2'){
 	 			$('#permissionExtSpan').text('AclId');
 	 			$('#cdtpDiv').hide();
 	 			$('#ljdxDiv').hide();
 	 		}
 	 	});
 		
 		$("#permissionInfoForm").validate({
 			  errorElement: 'span',
 			  errorClass:'help-inline',
 			  focusInvalid: false,ignore: '',
 			  rules: {permissionName: {minlength: 2,required: true,maxlength:20,
 				                 remote:{type:'post',url:'../power/checkPermissionName',data: {permissionName:function(){return $("#permissionName").val();}},
 				                	     dataType: "json",dataFilter:function (data) {return  data=='false'?true:false;}}},
 				      permissionOrder:{number:true,required:true,remote:{type:'post',url:'../power/checkPermissionOrder',data: {permissionOrder:function(){return $("#permissionOrder").val();},parentId:function(){return parentId;}},
	                	     dataType: "json",dataFilter:function (data) {return  data=='false'?true:false;}}},
 				      permissionExt1:{required:true},
 				      permissionDesc:{required:true},
 				      permissionUrl:{checkPost:true}},
 		      messages:{permissionName:{remote:'节点名已经存在,请重新变更'},
 		    	  		permissionOrder:{remote:'该排序已经存在,请重新变更'}},
 			  errorPlacement: function(error,element){error.insertAfter(element);},
 			 highlight: function(element) {
   			  $(element).closest('.control-group').removeClass('success');
   			  $(element).closest('.help-inline').removeClass('valid');
   			  $(element).closest('.help-inline').removeClass('ok');
   			  $(element).closest('.control-group').addClass('error');
   		  },
			  unhighlight: function(element) {$(element).closest('.control-group').removeClass('error');},
			  success: function(label) {
				  label.closest('.control-group').removeClass('error');
				  label.closest('.control-group').addClass('success');
				  label.closest('.help-inline').addClass('valid ok');
			  },
 			  submitHandler:function(form){
 				  $.post('../power/savePermission',$("#permissionInfoForm").serialize(),function(data){
 					  if(data.flg){
 						  $("#permissionInfoDiv").modal("hide");
 						  reloadTree();
 						  permissionDataTable.ajax.reload();
 						  swal("成功", "当前操作成功！", "success");
 					  }else{
 						  swal("失败", data.error, "error");
 					  }
 				  });
 			      return false;
 			  }});
 		$("#permissionInfoDiv").modal("show");
 	});
 	
 	//jquery自定义表单验证
 	jQuery.validator.addMethod("checkPost",function(value,element){
 		if($('#permissionType').val()=='1'){
 			if($('#permissionUrl').val()!=''&&$('#permissionUrl').val()!=undefined&&$('#permissionUrl').val()!=null){
 				return true;
 			}else{
 				return false;
 			}
 		}else if($('#permissionType').val()=='2'){
 			return true;
 		}
 	},"该输入框不能为空，请输入内容！");
});

//数据Tree重新加载
function reloadTree(){
	 $.post("../power/queryPermissions",function(data){
		 $.fn.zTree.init($("#permissionZTree"), setting,data).expandAll(true);});
}	